import React, { useState } from 'react';
import {
	DesktopOutlined,
	PieChartOutlined,
	TeamOutlined,
	UserOutlined,
} from '@ant-design/icons';
import { ItemType, MenuItemType } from 'antd/es/menu/hooks/useItems';
import { Menu } from 'antd';
import { useNavigate, useLocation,  } from "react-router-dom"

// 菜单目录
const items:ItemType<MenuItemType>[] = [
    { label:'Option 1', key:'/test1/index', icon:<PieChartOutlined />, },
    { label:'Option 2', key:'/test2/index', icon:<DesktopOutlined />, },
    { label:'User', key:'sub1', icon:<UserOutlined />, children:[
        { label:'Tom', key:'3', },
        { label:'Bill', key:'4', },
        { label:'Alex', key:'5', },
    ]},
    { label:'Team', key:'sub2', icon:<TeamOutlined />, children:[
        { label:'Team1', key:'6', },
        { label:'Team2', key:'8', },
    ]},
]

const Comp: React.FC = () => {
	const navigateTo = useNavigate();
    const currentRouter =  useLocation();

    // 点击跳转到对应路由 编程式导航跳转 利用到一个hook
	const menuClick = (e:{key:string}) => {
		navigateTo(e.key)
	}


    // 定义一个递归函数，用于遍历所有子节点
    let firstOpenKeys:string = '';
    const findRoot = (data:ItemType<MenuItemType>[], key:string): ItemType<MenuItemType> | null => {
        for (let item of data) {
            if (item!.key === key) {
              return item;
            }
            if (item && 'children' in item) {
                if (item && item?.children && Array.isArray(item.children)) {
                  let result = findRoot(item!.children, key);
                  if (result) {
                    return item;
                  }
                }
            }
        }
        return null;
    }
    // 默认展开当前路由匹配的菜单
    firstOpenKeys = findRoot(items, currentRouter.pathname)?.key as string || ''
    

    // 手风琴侧边栏
    const [openKeys, setOpenKeys] = useState([firstOpenKeys]);
	const handleOpenChange = (keys:string[]) => {
        setOpenKeys([keys[keys.length - 1]])
	}

    return (
        <div>
            <div className="home-logo" >12312</div>
            <Menu 
                theme="dark" 
                defaultSelectedKeys={[currentRouter.pathname]} 
                mode="inline" 
                items={ items } 
                onClick={ menuClick } 
                onOpenChange={ handleOpenChange }
                openKeys={ openKeys }
            />
        </div>
    )
}

export default Comp;